#include <iostream>
#include <string>
#include <stdexcept>
#include "SDL_image.h"
#include "SDL.h"
#include "SDL_ttf.h"
#include "sdltext.h"
#include "sdlbutton.h"
using namespace std;

SDLButton::SDLButton(std::string unclicked, std::string clicked, int x, int y, struct SDL_Surface *dst_screen, class SDLText *buttontext) throw (sdlbutton_error)
{
       button_unclicked_ = NULL;
       button_clicked_ = NULL;
       screen_ = dst_screen;
       clicked_ = false;

       // Load two images for each button. One for the unclicked
       // and one for the clicked.
       button_unclicked_ = IMG_Load(("adventure2/graphics/buttons/" + unclicked).c_str());
       if(button_unclicked_ == NULL)
       {
	      throw sdlbutton_error("Could not load " + unclicked + " for unclicked button!");
       }
       button_clicked_ = IMG_Load(("adventure2/graphics/buttons/" + clicked).c_str());
       if(button_clicked_ == NULL)
       {
	      throw sdlbutton_error("Could not load " + clicked + " for clicked button!");
       }

       // Check that both the buttons share the same
       // height and width.
       if(button_unclicked_->h != button_clicked_->h)
       {
	      throw sdlbutton_error("Height is different between unclicked and clicked button image!");
       }

       if(button_unclicked_->w != button_clicked_->w)
       {
	      throw sdlbutton_error("Width is different between unclicked and clicked button image!");
       }

       dst_.x = x;
       dst_.y = y;
       dst_.w = button_unclicked_->w;
       dst_.h = button_unclicked_->h;       

       // Position the text in the center of the button.
       buttontext->set_pos((((button_unclicked_->w)-(buttontext->get_width())) / 2), (((button_unclicked_->h)-(buttontext->get_height())) / 2));
       
       // Render the text on the buttons.
       buttontext->render(button_unclicked_);
       buttontext->render(button_clicked_);

       render();

}

SDLButton::~SDLButton()
{
       if(button_unclicked_ != NULL)
       {
	      SDL_FreeSurface(button_unclicked_);
       }
       if(button_clicked_ != NULL)
       {
	      SDL_FreeSurface(button_clicked_);
       }
}

bool SDLButton::is_clicked(int x, int y)
{
       clicked_ = false;

       // Check that the mouse is over an actual
       // button when it is clicked.
       if(x > dst_.x && x < dst_.x+dst_.w)
       {
	      if(y > dst_.y && y < dst_.y+dst_.h)
	      {		
		     clicked_ = true;
	      }
       }

       return clicked_;
}

void SDLButton::render()
{
       // If a button has been clicked then it should change appearence.
       if(clicked_ == true)
       {
	      SDL_BlitSurface(button_clicked_, NULL, screen_, &dst_);
	      clicked_ = false;
       }
       else
       {
	      SDL_BlitSurface(button_unclicked_, NULL, screen_, &dst_);
       }
}
